/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager;

import br.com.foxline.model.Charter;
import br.com.foxline.model.CharterSDI;
import br.com.foxline.model.Part;
import br.com.foxline.service.CharterService;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

/**
 *
 * @author roniere
 */
@ManagedBean
@SessionScoped
public class ManagerCensec {

    @EJB
    private CharterService charterService;
    private Charter charter;
    private Date dataIni;
    private Date dataFim;
    private Date dataIniCesdi;
    private Date dataFimCesdi;
    private Date dataIniRcto;
    private Date dataFimRcto;

    
    public void importTxtEscritura() throws IOException {
        int cont = 0;
        List<Charter> list = charterService.reportCensec(dataIni, dataFim);

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

        System.err.println("Qtd List: " + list.size());
        String txt = "/opt/glassfish3/CEP_" + sdf2.format(dataIni) + "_" + sdf2.format(dataFim) +".txt";;

        BufferedWriter writer = new BufferedWriter(new FileWriter(txt));

        writer.write("\"TIPOATOCEP\";\"NATUREZAESCRITURA\";\"DATAATO\";\"LIVRO\";\"LIVROCOMPLEMENTO\";\"FOLHA\";\"FOLHACOMPLEMENTO\";\"VALOR\";\"DESCONHECIDO\";\"REFERENTELIVRO\";\"REFERENTELIVROCOMPLEMENTO\";\"REFERENTEFOLHA\";\"REFERENTEFOLHACOMPLEMENTO\";\"REFERENTEUFORIGEM\";\"REFERENTECIDADEORIGEM\";\"REFERENTECARTORIO\";\"PARTENOME\";\"PARTEIDENTIDADE\";\"PARTEORGAOEMISSOR\";\"PARTETIPODOCUMENTO\";\"PARTENUMERODOCUMENTO\";\"PARTEQUALIDADE\"" + "\r");

        String line = "";
        String parteLine = "";
        for (Charter e : list) {
            Integer folha;
            Integer livro;
            
            try{
                folha = Integer.parseInt(e.getLeaf());
            }catch(Exception ex){
                folha = null;
            }
            
            try{
                livro = Integer.parseInt(e.getBook());
            }catch(Exception ex){
                livro = null;
            }
            
            line = "\"" + (e.getActCep() != null ? e.getActCep().getCod() : "") + "\";\""
                    + (e.getNatureWriting() != null ? e.getNatureWriting().getCod() : "") + "\";\""
                    + sdf.format(e.getDateAct()) + "\";\""
                    + livro
                    + "\";\"" + e.getBookComp() + "\";\""
                    + folha + "\";\""
                    + e.getLeafComp()
                    + "\";\"" + e.getCurrency()
                    + "\";\"" + //DESCONHECIDO 
                    "\";\"" + e.getRefBook()
                    + "\";\"" + e.getRefBookComp()
                    + "\";\"" + e.getRefleaf()
                    + "\";\"" + e.getRefleafComp()
                    + "\";\"" + (e.getUf() == null ? "" : e.getUf().getSlg())
                    + "\";\"" + (e.getCity() == null ? "" : e.getCity().getCodIbge())
                    + "\";\"" + e.getRefNotaryOffice();

            for (Part part : e.getParts()) {
                cont++;
                parteLine = line;
                if (part.getPeople() != null) {
                    parteLine += "\";\"" + (part.getPeople().getName() != null ? part.getPeople().getName() : "")
                            + "\";\"" + part.getPeople().getRg()
                            + "\";\"" + part.getPeople().getOrgan()
                            + "\";\"" + (part.getPeople().getTipoDocumento() == null? 
                                        (part.getPeople().getCpf() == null || part.getPeople().getCpf().isEmpty()? 
                                        (part.getPeople().getCnpj() == null || part.getPeople().getCnpj().isEmpty() ? "":"CNPJ"):
                                        "CPF"):part.getPeople().getTipoDocumento().getType())
                            + "\";\"" + (part.getPeople().getCpf() == null  || part.getPeople().getCpf().isEmpty() ? 
                            part.getPeople().getCnpj() : part.getPeople().getCpf())
                            + "\";\"" + (part.getPartQuality() != null ? part.getPartQuality().getDescription().replaceAll("\n|\t", "") : "") + "\"";
                    parteLine += "\r";
                    parteLine = parteLine.replace("null", "");
                    writer.write(parteLine);
                    //writer.newLine();
                }
            }
        }
        
        
        writer.flush();
        writer.close();
        fileEscritura(txt);
        System.err.println("FINALIZOU");
    }

    public void importTxtCesdi() throws IOException {
        List<CharterSDI> list = charterService.reportCesdi(dataIniCesdi, dataFimCesdi);

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

        String txt = "/opt/glassfish3/CESDI_" + sdf2.format(dataIniCesdi) + "_" + sdf2.format(dataFimCesdi) + "_.txt";

        BufferedWriter writer = new BufferedWriter(new FileWriter(txt));

        writer.write("\"TIPOATOCESDI\";\"DATAATO\";\"LIVRO\";"
                + "\"LIVROCOMPLEMENTO\";\"FOLHA\";\"FOLHACOMPLEMENTO\";"
                + "\"DATACASAMENTO\";\"REGIMEBENS\";\"QUANTIDADEFILHOMAIORES\";"
                + "\"NOMEPARTE\";\"QUALIDADE\";\"TIPODOCUMENTO1\";\"NUMERO1\";"
                + "\"UF1\";\"TIPODOCUMENTO2\";\"NUMERO2\";\"DATANASCIMENTO\";"
                + "\"LOCALNASCIMENTOPAIS\";\"LOCALNASCIMENTOUF\";\"LOCALRESIDENCIAPAIS\";"
                + "\"LOCALRESIDENCIAUF\";\"LOCALRESIDENCIAMUNICIPIO\";\"SEXO\"" + "\r");

        String line = "";
        String parteLine = "";
        for (CharterSDI e : list) {
            System.err.println("Censec: ");
            line = "\"" + (e.getActCep() != null ? e.getActCep().getCod() : "") + "\";\""
                    + sdf.format(e.getDateAct()) + "\";\""
                    + e.getBook() + "\";\""
                    + e.getBookComp() + "\";\""
                    + e.getLeaf() + "\";\""
                    + e.getLeafComp() + "\";\""
                    + sdf.format(e.getDateMarried()) + "\";\""
                    + //DESCONHECIDO 
                    "\";\"" + e.getPropertySystem().getName() + "\";\""
                    + e.getNumberAdultChildren();

            for (Part part : e.getParts()) {
                parteLine = line;
                if (part.getPeople() != null) {
                    parteLine += "\";\"" + part.getPeople().getName()
                            + "\";\"" + (part.getPartQuality() != null ? part.getPartQuality().getDescription().replaceAll("\n|\t", "") : "") + "\""
                            + "\";\"" + (part.getPeople().getCpf() != null ? "CPF" : (part.getPeople().getCnpj() != null ? "CNPJ" : "OAB"))
                            + "\";\"" + (part.getPeople().getCpf() != null ? part.getPeople().getCpf() : (part.getPeople().getCnpj() != null ? part.getPeople().getCnpj() : part.getPeople().getOAB()))
                            + "\";\"" + part.getPeople().getUFOAB()
                            + "\";\"" + (part.getPeople().getRg() != null ? "RG" : "" )
                            + "\";\"" + (part.getPeople().getRg() != null ? part.getPeople().getRg() : "" )
                            + "\";\"" + sdf.format(part.getPeople().getNasc())
                            + "\";\"" + (part.getPeople().getLocalNascimentoPais())
                            + "\";\"" + (part.getPeople().getLocalNascimentoUF() != null ? part.getPeople().getLocalNascimentoUF().getSlg():"")
                            + "\";\"" + (part.getPeople().getLocalResidenciaPais() != null ? part.getPeople().getLocalResidenciaPais():"")
                            + "\";\"" + (part.getPeople().getLocalResidenciaUF() != null ? part.getPeople().getLocalResidenciaUF().getSlg():"")
                            + "\";\"" + (part.getPeople().getLocalResidenciaMunicipio() != null ? part.getPeople().getLocalResidenciaMunicipio().getCodIbge():"")
                            + "\";\"" + (part.getPeople().getGender())+ "\";\"";

                    parteLine = parteLine.replace("null", "");
                    writer.write(parteLine);
                    writer.newLine();
                }
            }
        }
        writer.flush();
        writer.close();
        fileEscritura(txt);
        System.err.println("FINALIZOU");
    }

    public Date getDataFimCesdi() {
        return dataFimCesdi;
    }

    public void setDataFimCesdi(Date dataFimCesdi) {
        this.dataFimCesdi = dataFimCesdi;
    }

    public Date getDataFimRcto() {
        return dataFimRcto;
    }

    public void setDataFimRcto(Date dataFimRcto) {
        this.dataFimRcto = dataFimRcto;
    }

    public Date getDataIniCesdi() {
        return dataIniCesdi;
    }

    public void setDataIniCesdi(Date dataIniCesdi) {
        this.dataIniCesdi = dataIniCesdi;
    }

    public Date getDataIniRcto() {
        return dataIniRcto;
    }

    public void setDataIniRcto(Date dataIniRcto) {
        this.dataIniRcto = dataIniRcto;
    }

    
    public Charter getCharter() {
        return charter;
    }

    public void setCharter(Charter charter) {
        this.charter = charter;
    }

    public Date getDataFim() {
        return dataFim;
    }

    public void setDataFim(Date dataFim) {
        this.dataFim = dataFim;
    }

    public Date getDataIni() {
        return dataIni;
    }

    public void setDataIni(Date dataIni) {
        this.dataIni = dataIni;
    }

    public void fileEscritura(String txt) throws IOException {

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.setResponseHeader("Content-Type", "txt");
        externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + txt.replace("/opt/glassfish3/", "") + "\"");
        externalContext.getResponseOutputStream().write(recuperaFileEmByte(new File(txt)));
        facesContext.responseComplete();

    }

    private byte[] recuperaFileEmByte(File inFile) {
        InputStream is = null;
        byte[] buffer = null;
        try {
            is = new FileInputStream(inFile);
            buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
